package com.europe.business.europebusiness.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.europe.business.europebusiness.R;
import com.europe.business.europebusiness.ui.activity.base.ActionBarActivity;
import com.europe.business.europebusiness.ui.adapter.ListAdapter;
import com.europe.business.europebusiness.ui.adapter.MultiItemTypeSupport;
import com.europe.business.europebusiness.ui.adapter.MutilItemCommonAdapter;
import com.europe.business.europebusiness.ui.adapter.viewholder.ListViewHolder;
import com.europe.business.europebusiness.ui.bean.CompanyCategoryBean;
import com.europe.business.europebusiness.ui.bean.CountryBean;
import com.europe.business.europebusiness.ui.common.Commons;
import com.europe.business.europebusiness.ui.net.ICompany;
import com.europe.business.europebusiness.ui.net.IUser;
import com.europe.business.europebusiness.ui.utils.Utils;
import com.europe.business.europebusiness.ui.view.ListScrollerListener;


import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ListActivity<T> extends ActionBarActivity implements ListAdapter.ItemClicked {
    private static final String TAG = "ListActivity";
    private RecyclerView recyclerView;
    List<CompanyCategoryBean.Data> list;
    public static final int FALG_COUNTRY = 11;
    public static final int FALG_CITY = 12;
    public static final int FALG_SORT = 13;
    List<CountryBean.Country> countryList;
    private static final int PAGE_SIZE = 20;
    private int pageNum = 1;
    private int flag;
    MutilItemCommonAdapter mutilItemCommonAdapter;

    enum ListMoreStuts {
        LOADING,//加载中
        LOADED,//一次加载完成
        LOAD_COMPLETED, //已经到底
        LOAD_FAILURE //加载失败
    }

    ListMoreStuts moreStuts;
    List<T> listData;

    public void setListData(List<T> listData) {
        this.listData = listData;
    }

    public List<T> getListData() {
        return listData = listData;
    }

    @Override
    protected int setMainContent() {
        return R.layout.activity_info_select_list;
    }

    @Override
    protected void initView() {
        super.initView();
        setToolbarNavigationIcon(R.drawable.actionbar_back);
        setActionRight(false, "", null);
        recyclerView = findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setOnScrollListener(new ListScrollerListener() {
            @Override
            public void onPageNext() {
                Log.e(TAG, "------onPageNext------");
                if (moreStuts == ListMoreStuts.LOAD_COMPLETED) {
                    return;
                }
                int dataCount = mutilItemCommonAdapter.getDataCount();
                mutilItemCommonAdapter.setIsHaveFoot(1);
                moreStuts = ListMoreStuts.LOADING;
                mutilItemCommonAdapter.notifyDataSetChanged();
                recyclerView.scrollToPosition(dataCount);

                //调用接口，请求数据
                pageNum++;
                if (flag == FALG_SORT) {
                    getSortData();
                } else if (flag == FALG_COUNTRY) {
                    getCountryData();
                }
            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
        countryList = new ArrayList<CountryBean.Country>();
        flag = getIntent().getIntExtra("flag", -1);
        if (flag == FALG_SORT) {
            getSortData();
            setTitle(getString(R.string.info_select_sort));
        } else if (flag == FALG_COUNTRY) {
            getCountryData();
            setTitle(getString(R.string.info_select_city1));
        } else {
            getData();
        }

    }

    protected void getData() {

    }

    /**
     * 获取国家数据
     */
    private void getCountryData() {
        if (pageNum == 1) {
            showProgressDialog();
        }

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Commons.SERVER_URL)
                .build();
        ICompany company = retrofit.create(ICompany.class);
        Call<CountryBean> call = company.getCountryList(pageNum, PAGE_SIZE, Utils.getSystemLanguage(this));
        call.enqueue(new Callback<CountryBean>() {
            @Override
            public void onResponse(Call<CountryBean> call, Response<CountryBean> response) {
                dismissProgressDialog();
                if (null != mutilItemCommonAdapter) {
                    mutilItemCommonAdapter.setIsHaveFoot(1);
                }
                final CountryBean bean = response.body();
                if (null != bean) {
                    if (bean.getErrorCode() == 1) {
                        if (countryList.size() == 0) {
                            countryList = bean.getData();
                        } else {
                            countryList.addAll(bean.getData());
                        }

                        MultiItemTypeSupport<CountryBean.Country> multiItemTypeSupport = new MultiItemTypeSupport<CountryBean.Country>() {
                            @Override
                            public int getLayoutId(int type) {
                                if (type == MutilItemCommonAdapter.VIWE_TYPE_DATA) {
                                    return R.layout.activity_text_item;
                                } else {
                                    return R.layout.item_foot_company;
                                }
                            }

                            @Override
                            public int getItemViewType(int position) {
                                if (position == countryList.size()) {
                                    return MutilItemCommonAdapter.VIWE_TYPE_FOOT;
                                } else {
                                    return MutilItemCommonAdapter.VIWE_TYPE_DATA;
                                }
                            }
                        };
                        moreStuts = ListMoreStuts.LOADED;
                        if (mutilItemCommonAdapter == null) {
                            mutilItemCommonAdapter = new MutilItemCommonAdapter<CountryBean.Country>(ListActivity.this, countryList, multiItemTypeSupport, ListActivity.this) {
                                @Override
                                public void convert(ListViewHolder holder, CountryBean.Country o) {
                                    if (o == null) {
                                        ProgressBar progressBar = holder.getView(R.id.progress);
                                        TextView textView = holder.getView(R.id.loading);
                                        switch (moreStuts) {
                                            case LOADED:
                                                progressBar.setVisibility(View.GONE);
                                                textView.setText(getString(R.string.loaded));
                                                break;
                                            case LOADING:
                                                progressBar.setVisibility(View.GONE);
                                                textView.setText(getString(R.string.loading));
                                                break;
                                            case LOAD_FAILURE:
                                                progressBar.setVisibility(View.GONE);
                                                textView.setText(getString(R.string.load_failure));
                                                break;
                                            case LOAD_COMPLETED:
                                                progressBar.setVisibility(View.GONE);
                                                textView.setText(getString(R.string.load_over));
                                                break;
                                        }

                                    } else {
                                        TextView tv = holder.getView(R.id.tv);
                                        tv.setText(o.getName());
                                    }

                                }
                            };
                            recyclerView.setAdapter(mutilItemCommonAdapter);
                        } else {
                            mutilItemCommonAdapter.notifyDataSetChanged();
                        }

                    } else {
                        if (bean.getErrorCode() == 1001) {//没有更多数据
                            moreStuts = ListMoreStuts.LOAD_COMPLETED;
                            showToastLong(getString(R.string.info_list_no_more_data));
                        } else {
                            moreStuts = ListMoreStuts.LOAD_FAILURE;
                            showToastLong(bean.getErrorMessage());
                        }
                        mutilItemCommonAdapter.notifyDataSetChanged();
                    }

                } else

                {
                    moreStuts = ListMoreStuts.LOAD_FAILURE;
                    if(null != mutilItemCommonAdapter)
                    mutilItemCommonAdapter.notifyDataSetChanged();
                    showToastLong(getString(R.string.requst_failed));
                }
            }

            @Override
            public void onFailure(Call<CountryBean> call, Throwable t) {
                moreStuts = ListMoreStuts.LOAD_FAILURE;
                if (null != ListMoreStuts.LOAD_FAILURE) {
                    mutilItemCommonAdapter.setIsHaveFoot(1);
                    mutilItemCommonAdapter.notifyDataSetChanged();
                }
                dismissProgressDialog();
                showToastLong(getString(R.string.requst_failed));
            }
        });
    }


    /**
     * 获取企业类型数据
     */
    private void getSortData() {
        showProgressDialog();
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Commons.SERVER_URL)
                .build();
        ICompany company = retrofit.create(ICompany.class);
        Call<CompanyCategoryBean> call = company.getCompanyCategory(pageNum,PAGE_SIZE,Utils.getSystemLanguage(this));
        call.enqueue(new Callback<CompanyCategoryBean>() {
            @Override
            public void onResponse(Call<CompanyCategoryBean> call, Response<CompanyCategoryBean> response) {
                dismissProgressDialog();
                CompanyCategoryBean bean = response.body();
                if (null != bean) {
                    if (bean.getErrorCode() == 1) {
                        list = bean.getData();
                        recyclerView.setAdapter(new ListAdapter<CompanyCategoryBean.Data>(ListActivity.this,
                                list, R.layout.activity_text_item, ListActivity.this) {
                            @Override
                            public void convert(ListViewHolder holder, CompanyCategoryBean.Data data) {
                                TextView tv = holder.getView(R.id.tv);
                                tv.setText(data.getCategory());
                            }
                        });
                    } else {
                        showToastLong(bean.getErrorMessage());
                    }
                } else {
                    showToastLong(getString(R.string.requst_failed));
                }

            }

            @Override
            public void onFailure(Call<CompanyCategoryBean> call, Throwable t) {
                dismissProgressDialog();
                Log.i("ListActivity", t.getMessage());
                showToastLong(getString(R.string.requst_failed));
            }
        });
    }


    public void onItemClicked(int index) {
        if (null != list) {
            String category = list.get(index).getCategory();
            Intent intent = new Intent();
            intent.putExtra("data", category);
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else if (null != countryList) {
            String name = countryList.get(index).getName();
            Intent intent = new Intent();
            intent.putExtra("data", name);
        }
    }
}
